package cn.edu.jxau.test;

import java.util.ArrayList;
import java.util.List;

/**
 * 使用DFS计算图中连通分量的个数
 * 
 * @author 付大石
 */
public class ConnectedComponent {

    public static void main(String[] args) {

        UndirectedGraph g = new UndirectedGraph(13);
        g.addEdge(0, 5);
        g.addEdge(4, 3);
        g.addEdge(0, 1);
        g.addEdge(9, 12);
        g.addEdge(6, 4);
        g.addEdge(5, 4);
        g.addEdge(0, 2);
        g.addEdge(11, 12);
        g.addEdge(9, 10);
        g.addEdge(0, 6);
        g.addEdge(7, 8);
        g.addEdge(9, 11);
        g.addEdge(5, 3);
        ConnectedComponent cc = new ConnectedComponent(g);
        System.out.println(GraphUtils.toString(g));
        int count = cc.count();
        System.out.println("component:" + count);
        List<Integer>[] componentList = new List[count];
        for (int i = 0; i < componentList.length; i++) {
            componentList[i] = new ArrayList<>();
        }
        for (int i = 0; i < g.v(); i++) {
            componentList[cc.id(i)].add(i);
        }
        for (List<Integer> component : componentList) {
            for (Integer i : component) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }

    private boolean[] marked;

    /**
     * 各个顶点的连通分量id
     */
    private int[] id;

    /**
     * 连通分量个数
     */
    private int count;

    public ConnectedComponent(Graph g) {

        marked = new boolean[g.v()];
        id = new int[g.v()];
        for (int i = 0; i < g.v(); i++) {
            if (!marked[i]) {
                dfs(g, i);
                count++;
            }
        }
    }

    private void dfs(Graph g, int v) {
        marked[v] = true;
        id[v] = count;
        for (int w : g.adj(v)) {
            if (!marked[w]) {
                dfs(g, w);
            }
        }
    }

    /**
     * v和w是否等价，或者说v和w是否连通
     * @param v
     * @param w
     * @return
     */
    public boolean connected(int v, int w) {
        return id[v] == id[w];
    }

    /**
     * 连通分量个数
     * @return
     */
    public int count() {
        return count;
    }

    /**
     * 顶点{@param v}的连通分量的id
     * @param v
     * @return
     */
    public int id(int v) {
        return id[v];
    }
}
